import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as apiLogin, type LoginRequest } from '@/api/account'

// 本地存储键名
const TOKEN_KEY = 'adx_token'
const USER_INFO_KEY = 'adx_user_info'

export const useUserStore = defineStore('user', () => {
  // 从本地存储初始化状态
  const token = ref<string>(localStorage.getItem(TOKEN_KEY) || '')
  const userInfo = ref<any>(JSON.parse(localStorage.getItem(USER_INFO_KEY) || 'null'))
  const isLoggedIn = ref<boolean>(!!token.value)

  const login = async (username: string, password: string) => {
    try {
      const loginParams: LoginRequest = {
        loginName: username,
        loginPassword: password
      }
      
      const result = await apiLogin(loginParams)
      
      // 保存token和用户信息到本地存储
      token.value = result.token
      userInfo.value = result.account
      isLoggedIn.value = true
      
      localStorage.setItem(TOKEN_KEY, result.token)
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(result.account))
      
      return { success: true }
    } catch (error: any) {
      console.error('登录失败:', error)
      return { 
        success: false, 
        message: error.message || '登录失败，请检查用户名和密码' 
      }
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    isLoggedIn.value = false
    
    // 清除本地存储
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(USER_INFO_KEY)
  }

  // 检查登录状态（用于页面刷新后重新验证）
  const checkLoginStatus = () => {
    const storedToken = localStorage.getItem(TOKEN_KEY)
    if (storedToken) {
      token.value = storedToken
      userInfo.value = JSON.parse(localStorage.getItem(USER_INFO_KEY) || 'null')
      isLoggedIn.value = true
      return true
    }
    return false
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    checkLoginStatus
  }
})